const mysql = require('mysql')
const config = require('../config')

const poolDict = {}

function getPool (key = config.env) {
  if (poolDict[key]) return poolDict[key]

  poolDict[key] = mysql.createPool(config.get(key).dbconfig)

  return poolDict[key]
}

/**
 * @param {string} sql
 * @param {object|any[]} [params]
 * @return {Promise<object|object[]>}
 * **/
function exec (sql, params = [], connect) {
  return new Promise((resolve, reject) => {
    connect = connect || poolDict[config.env]

    connect.query(sql, params, (err, result) => {
      if (err) return reject(err)

      resolve(result)
    })
  })
}

const defaultPool = getPool()

module.exports = defaultPool
module.exports.getPool = getPool
module.exports.exec = exec
